'''
盛放人生——全球癌症医疗保险
'''

import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
from urllib.parse import urlencode
import requests,json
from common.helper import Helper


class Spider(object):
    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "盛放人生——全球癌症医疗保险"

    # 生成产品数据
    def genProductInfo(self):

        plan = {

            "year": [str(i) for i in range(0, 64)],
            # 性别 M 男 F 女
            "gender": ["M", "F"],
            # 计划代码
            "planCode": ["CMI001", "CMI002", "CMI003", "CMI004"],
            # 保障期限
            "expire": ["1年"],

        }

        for v in product(plan["year"], plan["gender"], plan["planCode"], plan["expire"]):

            if v[2] == "CMI001":

                introduce = {

                    "plan": "全球计划(含美国、20%自付)"
                }

            elif v[2] == "CMI002":

                introduce = {

                    "plan": "全球计划(含美国、无自付)"
                }

            elif v[2] == "CMI003":

                introduce = {

                    "plan": "国际计划(除美国、20%自付)"
                }

            else:

                introduce = {

                    "plan": "国际计划(除美国、无自付)"
                }

            # 写入数据库
            data = "'" + json.dumps(introduce, ensure_ascii=False) + "'"

            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], data))
            self.mysql._conn.commit()

            print(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], data))

    # 执行爬虫
    def requestJson(self, dt=None):

        dt = self.mysql.randTask(self.name)

        print(dt)

        data = {

            "customerClass": "",
            "saleSourceCode": "",
            "customerCode": "",
            "activityCode": "",
            "telmapingId": "",
            "salesRelationId": "70451",
            "cityCode": "310100",
            "cityName": "上海市",
            "provinceCode": "310000",
            "provinceName": "上海市",
            "insureBgeinNum": "1",
            "insureEndNum": "366",
            "planCode": "CMI",
            "departmentCode": "5",
            "pageInfo": "bralirantTravel",
            "analysisPageInfo": "luck_index",
            "isAgent": "null",
            "ms": "HealthCP_2019_PCmenu",
            "insuredNum": "1",
            "isSave": "true",
            "userName": "",
            "insureDays": "365",
            "openCmsUrl": "https: // www.axa.cn",
            "planDefineId": dt["planCode"],
            "firstPlanId": "CMI001",
            "pension": "1",
            "isAjax": "1",
            "allYear": "1",
            "gender": dt["gender"],
            "isPc": "Y",
            "isDiscount": "",
            "rebate": "",
            "gender": dt["gender"],
            "select_city": "上海市",
            "contractBeginDate": "2020- 01-09",
            "contractEndDate": "2021-01-08",
            "insuredBirth": "{year}-12-25".format(year=str(2019 - int(dt["year"]))),
            "requestTypeIsAjax": "1",
        }

        payload = urlencode(data).replace("+", '')

        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)


        if r.status_code == 200 and r.json()["status"] == "success":

            price = Helper.decimalParse( r.json()["data"]["totalActualPremium"] )

            data = {

                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )

        else:

            # 任务执行失败
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.updateTask(data)
            print("产品价格更新失败:", dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)


